package main.java.indi.zyj.acm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Merge {

    public int[][] merge(int[][] intervals) {

        Arrays.sort(intervals, (int[] interval1, int[] interval2) -> interval1[0] - interval2[0]);

        List<int []> res = new ArrayList<>();

        for (int i = 0; i < intervals.length; i++) {
            int left = intervals[i][0];
            int right = intervals[i][1];
            if (res.size() == 0 || res.get(res.size() - 1)[1] < left) {
                res.add(intervals[i]);
            } else {
                res.get(res.size() - 1)[1] = Math.max(right, res.get(res.size() - 1)[1]);
            }
        }

        return res.toArray(new int[res.size()][]);

    }

}
